package com.warehouse.dao.impl;

import com.warehouse.dao.CargotypeDao;
import com.warehouse.dao.common.HibernateUtil;
import com.warehouse.entity.Cargo;
import com.warehouse.entity.Cargotype;
import org.hibernate.Query;

import java.util.List;

public class CargotypeDapImpl implements CargotypeDao {
    //增加
    @Override
    public int add(Cargotype cargotype) {
        try {
            HibernateUtil.currentSession().save(cargotype);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
        return 1;
    }
    //修改
    @Override
    public int update(Cargotype cargotype) {
        try {
            HibernateUtil.currentSession().update(cargotype);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
        return 1;
    }
    //删除
    @Override
    public int delete(int id) {
        try {
            //先获取id
            Cargotype cargotype = (Cargotype) HibernateUtil.currentSession().get(Cargotype.class, id);
            HibernateUtil.currentSession().delete(cargotype);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
        return 1;
    }
    //分页
    @Override
    public List<Cargotype> allPage(int startPage, int pageSize) {
        Query query = HibernateUtil.currentSession().createQuery("from Cargotype");
        query.setFirstResult(startPage);
        query.setMaxResults(pageSize);
        return query.list();
    }
    //总条数
    @Override
    public int count() {
        return HibernateUtil.currentSession().createQuery("from Cargotype").list().size();
    }
    //根据id查询内容
    @Override
    public Cargotype byId(int id) {
        Cargotype cargotype = (Cargotype) HibernateUtil.currentSession().get(Cargotype.class,id);
        return cargotype;
    }

    @Override
    public List<Cargotype> byAdminNum(int startPage, int pageSize, String name) {
        Query query = HibernateUtil.currentSession().createQuery("from Cargotype c where c.name like '%" + name + "%'");
        query.setFirstResult(startPage);
        query.setMaxResults(pageSize);
        return query.list();
    }

    @Override
    public int countByAdminNum(String name) {
        return HibernateUtil.currentSession().createQuery("from Cargotype c where c.name like '%" + name + "%'").list().size();
    }

    @Override
    public List<Cargotype> all() {
        return (List<Cargotype>)HibernateUtil.currentSession().createQuery("from Cargotype c").list();
    }
}
